package com.example.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;

public class ShiroApplication {

    public static void main(String[] args) {
        //1.初始化获取SecurityManager
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        //2.获取subject对象
        Subject subject = SecurityUtils.getSubject();
        //3.创建token对象，web应用用户名和密码从页面传递
        UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "z3");
        try {
            //4.完成登录
            subject.login(token);
            System.out.println("登录成功");
            // 判断角色
            boolean haseRole = subject.hasRole("role1");
            System.out.println("haseRole:"+haseRole);
            // 判断权限
            boolean permitted = subject.isPermitted("user:insert");
            System.out.println("hasPermit:"+permitted);
            // 检查权限
            subject.checkPermission("user:insert");
        } catch (UnknownAccountException e) {
            System.out.println("用户不存在");
        }catch (IncorrectCredentialsException e){
            System.out.println("密码错误");
        }catch (AuthenticationException e){
            System.out.println("登录失败");
        }
    }

}
